package com.ronsai.umtrack.activity;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.KeyGenerator;
import com.qiniu.android.storage.Recorder;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;
import com.qiniu.android.storage.persistent.FileRecorder;
import com.ronsai.umtrack.MyApp;
import com.ronsai.umtrack.R;
import com.ronsai.umtrack.api.ObserverResponseListener;
import com.ronsai.umtrack.base.BaseActivity;
import com.ronsai.umtrack.base.BasePresenter;
import com.ronsai.umtrack.base.BaseView;
import com.ronsai.umtrack.model.UploadModel;
import com.ronsai.umtrack.util.MediaFileUtil;
import com.ronsai.umtrack.util.ToastUtil;
import com.ronsai.umtrack.util.UriUtils;
import com.ronsai.umtrack.util.permission.PermissionCallback;
import com.ronsai.umtrack.util.permission.PermissionUtil;
import com.yanzhenjie.permission.Permission;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;

public class QiniuActivitiy extends BaseActivity {

    @BindView(R.id.select_image_tv)
    TextView selectImageTv;
    @BindView(R.id.select_radio_tv)
    TextView selectRadioTv;
    @BindView(R.id.select_video_tv)
    TextView selectVideoTv;

    private UploadModel<String> uploadModel;
    private UploadManager uploadManager;
    private SimpleDateFormat sdf;
    private ProgressDialog progressDialog;
    private boolean isCancelled = false;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_qiniu;
    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected BaseView createView() {
        return null;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        uploadModel = new UploadModel<>();
        Recorder recorder = null;
        try {
            recorder = new FileRecorder(mContext.getCacheDir().getAbsolutePath());
        } catch (IOException e) {
            e.printStackTrace();
        }
        KeyGenerator keyGen = new KeyGenerator() {
            public String gen(String key, File file) {
                return key + "_._" + new StringBuffer(file.getAbsolutePath()).reverse();
            }
        };
        Configuration config = new Configuration.Builder()
                .recorder(recorder, keyGen) // 断点续传记录
                .build();
        uploadManager = new UploadManager(config);
        sdf = new SimpleDateFormat("yyyyMMddHHmmss");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK || data == null) return;
        Uri selectImageUri = data.getData();
        // 获取真实的路径
        String path = "";
        try {
            path = UriUtils.getPath(mContext, selectImageUri);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (TextUtils.isEmpty(path) || !new File(path).exists()) {
            ToastUtil.showShortToast("无法加载该文件");
            return;
        }
        switch (requestCode) {
            case 100:
                String imageKey = "icon_" + path + sdf.format(new Date());
                uploadFile(path, imageKey);
                break;
            case 200:
                // 判断文件类型
                if (!(path.endsWith(".mp3") || path.endsWith(".m4a"))) {
                    ToastUtil.showShortToast("请上传mp3或m4a音频文件");
                    return;
                }
                String radioKey = "radio_" + path + sdf.format(new Date());
                uploadFile(path, radioKey);
                break;
            case 300:
                // 判断文件类型
                if (!MediaFileUtil.isVideoFileType(path)) {
                    ToastUtil.showShortToast("请上传视频文件，推荐上传mp4文件");
                    return;
                }
                // 文件大小限制
                File file = new File(path);
                if (file.length() > 5368709120L) {
                    ToastUtil.showShortToast("请选择不超过5G的视频上传哦");
                    return;
                }
                String videoKey = "video_" + path + sdf.format(new Date());
                uploadFile(path, videoKey);
                break;
        }
    }

    private void showUploadDialog() {
        progressDialog = new ProgressDialog(mContext);
        progressDialog.setTitle("文件上传中");
        progressDialog.setCancelable(false);
        progressDialog.setIndeterminate(false);
        progressDialog.setMax(100);
        progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", (dialogInterface, i) -> {
            progressDialog.dismiss();
            isCancelled = true;
        });
        progressDialog.show();
    }

    private void uploadFile(String path, String key) {
        if (TextUtils.isEmpty(path)) {
            Log.e("log_test", "upload -- path null");
            return;
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("token", MyApp.getToken());
        uploadModel.getQiniuUploadToken(mContext, map, new ObserverResponseListener<String>() {
            @Override
            public void onSuccess(String s) {
                showUploadDialog();
                isCancelled = false;
                new Thread(() -> uploadManager.put(new File(path), key, s, (key1, info, response) -> {
                    progressDialog.dismiss();
                    if (info.isOK()) {
                        ToastUtil.showShortToast("上传成功");
                        Log.d("log_test", "upload success: " + key1);
                    } else {
                        ToastUtil.showShortToast("上传失败");
                        Log.e("log_test", "upload failed: " + info.error);
                    }
                }, new UploadOptions(null, null, false, (key12, percent) -> {
                    Log.d("log_test", "upload percent: " + percent);
                    if (progressDialog != null) progressDialog.setProgress((int) (percent * 100));
                }, () -> isCancelled))).start();
            }

            @Override
            public void onError(int code, String msg) {
                Log.e("log_test", "getUploadToken error: " + msg);
                progressDialog.dismiss();
            }
        });
    }

    @OnClick({R.id.select_image_tv, R.id.select_radio_tv, R.id.select_video_tv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.select_image_tv:
                PermissionUtil.requestPermission(mContext, new PermissionCallback() {

                    @Override
                    public void onGranted() {
                        Intent intent = new Intent();
                        intent.setType("image/*");
                        intent.setAction(Intent.ACTION_PICK);
                        startActivityForResult(intent, 100);
                    }

                    @Override
                    public void onDenied() {

                    }
                }, Permission.Group.STORAGE);
                break;
            case R.id.select_radio_tv:
                PermissionUtil.requestPermission(mContext, new PermissionCallback() {

                    @Override
                    public void onGranted() {
                        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                        intent.setType("*/*");
                        intent.addCategory(Intent.CATEGORY_OPENABLE);
                        startActivityForResult(intent, 200);
                    }

                    @Override
                    public void onDenied() {

                    }
                }, Permission.Group.STORAGE);
                break;
            case R.id.select_video_tv:
                PermissionUtil.requestPermission(mContext, new PermissionCallback() {

                    @Override
                    public void onGranted() {
                        Intent intent = new Intent();
                        intent.setType("video/*");
                        intent.setAction(Intent.ACTION_GET_CONTENT);
                        startActivityForResult(intent, 300);
                    }

                    @Override
                    public void onDenied() {

                    }
                }, Permission.Group.STORAGE);
                break;
        }
    }
}
